package com.jiepu.exercise.advanceed.chapter6;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.Scanner;

/**
 * @Description: 复制十个副本
 * @author: xinjie
 * @date: 2020/8/7  8:55
 */
public class CopyDemo3 {
	private static int buffersize = 128;


	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		File file = null;

		// 输入复制文件路径
		do {
			System.out.println("Input Copyed FileName: ");
			String input = scanner.nextLine();
			file = new File(input);

		} while (!file.exists());

		// 复制次数
		int copycount = -1;
		do {
			System.out.println("Input copy times:");

			try {
				copycount = scanner.nextInt();
			} catch (Exception e) {
				System.out.println("   ");
			}

		} while (copycount <= 0);
		System.out.println("copy .....");
		//
		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			// 创建一个容器 保存输出流
			List<OutputStream> list = new ArrayList<>();
			OutputStream[] outputStreams = new OutputStream[copycount];

			// 一个输入流对应 copycount个 输出流
			for (int i = 0; i < copycount; i++) {
				File copyName = getNextCopyName(file, i + 1);
				outputStreams[i] = new FileOutputStream(copyName);

			}
			// 输入流开始读取
			byte[] buff = new byte[buffersize];
			int len = -1;
			while ((len = fileInputStream.read(buff)) != -1) {
				for (OutputStream ops : outputStreams) {
					ops.write(buff, 0, len);

				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}


	} // main

	/**
	 * @param sourFile 源文件
	 * @param count    复制次数
	 * @return 副本文件
	 */
	public static File getNextCopyName(File sourFile, int count) {
		// 简略名称
		String simpleName = sourFile.getName();

		simpleName.replaceAll("\\."," - copy" + count + ".");


		/*//
		String[] fixes = simpleName.split("\\.");
		String prefix = fixes[0]
		String sufix = fixes[1];

		prefix = prefix + "-  副本" + count;
		simpleName = prefix + "."+sufix;*/



		return new File(sourFile.getParent(),simpleName);

	}

}
